import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ivy_baby_record/user/api/verify/verify.impl.dart';
import 'package:ivy_baby_record/ivy_baby_record.dart';
import 'package:ivy_baby_record/user/constants/route_page.dart';
import 'package:ivy_baby_record/user/db/user_database_util.dart';
import 'package:ivy_baby_record/user/pages/base/init_reg_base.dart';
import 'package:ivy_baby_record/user/util/log.dart';
import 'package:ivy_baby_record/user/util/ui_util.dart';
import 'package:ivy_baby_record/user/widget/flatbutton.dart';
import 'package:ivybaby_api/api/base/api_base.dart';
import 'package:ivy_baby_record/user/colors/colors.dart';
import 'package:provider/provider.dart';

class InitChildPage extends InitRegLoginPage {
  @override
  State<StatefulWidget> createState() => _InitChildPageState();
}

class _InitChildPageState extends InitRegLoginPageState<InitChildPage> {
  PageController? _pageController;
  int _currentPage = 0;
  String _gestationWeek = '';

  StatusChangeNotifier? statusChangeNotifier;
  ValueNotifier<int> questionTextureNotifier = ValueNotifier(-1);
  ValueNotifier<bool> agreementNotifier = ValueNotifier(false);
  ValueNotifier<bool> prematureNotifier = ValueNotifier(false);
  ValueNotifier<String> dateNotifier = ValueNotifier('');

  @override
  bool get showTitle => false;

  @override
  void initState() {
    super.initState();

    loadImageWithTexture();
    _pageController = PageController();
    _pageController?.addListener(() {
      var offset = _pageController!.offset;
      var page = _pageController!.page;
    });
  }

  @override
  bool onKeyCodeBackClick(BuildContext context) {
    IvyBabyRecord.release('initial_question_bg');
    return super.onKeyCodeBackClick(context);
  }

  @override
  Widget buildDetailContent(BuildContext context) {
    return buildPageView(context);
  }

  Widget buildPageView(BuildContext context) {
    Log.i('init_child', 'build page view');
    return Container(
      child: ChangeNotifierProvider(
        create: (context) => statusChangeNotifier = StatusChangeNotifier(),
        child: Consumer<StatusChangeNotifier>(
          builder: (context, status, child) {
            return PageView.builder(
                onPageChanged: (index) {
                  _currentPage = index;
                },
                reverse: false,
                physics: status._gestation < 0
                    ? NeverScrollableScrollPhysics()
                    : BouncingScrollPhysics(),
                scrollDirection: Axis.horizontal,
                controller: _pageController,
                itemCount: 2,
                itemBuilder: (context, index) {
                  return index == 0
                      ? buildStateSelectWidget(context)
                      : buildDateSetWidget(context);
                });
          },
        ),
      ),
    );
  }

  Widget buildStateSelectWidget(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          alignment: Alignment.center,
          height: 280,
          margin: EdgeInsets.symmetric(horizontal: 30),
          padding: EdgeInsets.symmetric(vertical: 40),
          decoration: BoxDecoration(
            color: Color.fromARGB(0x26, 0xFF, 0xFF, 0xFE),
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
          child: Consumer<StatusChangeNotifier>(
            builder: (context, status, child) {
              return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('你的当前状态是？',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                  SizedBox(height: 30),
                  FlatButton(
                    minimumSize: Size(160, 54),
                    // minWidth: 160,
                    // height: 54,
                    backgroundColor: status._gestation != 1 ? Colors.transparent : Colors.white,
                    textColor: status._gestation != 1 ? Colors.white : CustomColors.c8,
                    // highlightColor: Colors.white,
                    onPressed: () {
                      if (status._gestation != 1) {
                        dateNotifier.value = '';
                      }
                      status.update(1);
                      _pageController?.jumpToPage(1);
                    },
                    fontSize: 20,
                    child: Text('孕期'),
                    shape: RoundedRectangleBorder(
                        side: status._gestation != 1
                            ? BorderSide(color: Colors.white)
                            : BorderSide.none,
                        borderRadius: BorderRadius.all(Radius.circular(27))),
                  ),
                  SizedBox(height: 15),
                  FlatButton(
                    // minWidth: 160,
                    // height: 54,
                    fontSize: 20,
                    minimumSize: Size(160, 54),
                    textColor: status._gestation != 0 ? Colors.white : CustomColors.c8,
                    // highlightColor: Colors.white,
                    backgroundColor: status._gestation != 0 ? Colors.transparent : Colors.white,
                    onPressed: () {
                      if (status._gestation != 0) {
                        dateNotifier.value = '';
                      }
                      status.update(0);
                      _pageController?.jumpToPage(1);
                    },
                    child: Text('育儿期'/*, style: TextStyle(fontSize: 20)*/),
                    shape: RoundedRectangleBorder(
                        side: status._gestation != 0
                            ? BorderSide(color: Colors.white)
                            : BorderSide.none,
                        borderRadius: BorderRadius.all(Radius.circular(27))),
                  ),
                ],
              );
            },
          ),
        ),
        Positioned(
            top: (ScreenUtil().screenHeight - 280) / 2 - 80,
            child: Text('欢迎来到育学园',
                style: TextStyle(fontSize: 32, color: Colors.white))),
        Positioned(
          bottom: ScreenUtil().setWidth(70),
          child: RichText(
            text: TextSpan(
                style: TextStyle(fontSize: 16, color: Colors.white),
                children: [
                  TextSpan(text: '已有账号，点此'),
                  TextSpan(
                      text: '登录',
                      style: TextStyle(
                          fontSize: 16,
                          color: Colors.white,
                          decoration: TextDecoration.underline),
                      recognizer: TapGestureRecognizer()
                        ..onTap = () {
                          Navigator.of(context).pushNamed('login');
                        }),
                ]),
          ),
        ),
      ],
    );
  }

  Widget buildDateSetWidget(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          alignment: Alignment.center,
          height: 280,
          margin: EdgeInsets.symmetric(horizontal: 30),
          padding: EdgeInsets.symmetric(vertical: 40),
          decoration: BoxDecoration(
            color: Color.fromARGB(0x26, 0xFF, 0xFF, 0xFE),
            borderRadius: BorderRadius.all(Radius.circular(12)),
          ),
          child: Consumer<StatusChangeNotifier>(
            builder: (context, status, child) {
              return Column(
                children: [
                  Text(status._gestation == 1 ? '预产期' : '宝宝的信息',
                      style: TextStyle(color: Colors.white, fontSize: 20)),
                  SizedBox(height: 16),
                  GestureDetector(
                    onTap: () {
                      UIUtils.showCustomDatePicker(context, status._gestation == 1, (dateTime) {
                        dateNotifier.value = dateTime.toString().split(' ')[0];
                      });
                    },
                    child: Container(
                      width: 200,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          ValueListenableBuilder<String>(
                            valueListenable: dateNotifier,
                            builder: (context, value, child) {
                              return Text(
                                value.isEmpty
                                    ? (status._gestation == 1 ? '选择日期' : '出生日期')
                                    : value,
                                style: TextStyle(
                                  fontSize: 24,
                                  color:
                                  value.isEmpty ? Colors.white54 : Colors.white,
                                ),
                              );
                            },
                          ),
                          Divider(height: 1, color: Colors.white)
                        ],
                      ),
                    ),
                  ),
                  Offstage(
                    offstage: status._gestation == 0,
                    child: Container(
                      alignment: Alignment.center,
                      margin: EdgeInsets.only(top: 25),
                      child: Text('还不确定，帮我计算',
                          style: TextStyle(fontSize: 14, color: Colors.white60)),
                    ),
                  ),
                  Offstage(
                    offstage: status._gestation == 1,
                    child: Container(
                      margin: EdgeInsets.only(top: 25),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            width: 12,
                            height: 12,
                            margin: EdgeInsets.only(right: 2),
                            child: GestureDetector(
                              onTap: () {
                                prematureNotifier.value = !prematureNotifier.value;
                              },
                              child: ValueListenableBuilder(
                                valueListenable: prematureNotifier,
                                builder: (context, value, child) {
                                  return UIUtils.getWidgetByTextureId(value != null
                                      ? checkTextureId
                                      : uncheckTextureId);
                                },
                              ),
                            ),
                          ),
                          Text('宝宝是早产儿',
                              style:
                              TextStyle(fontSize: 14, color: Colors.white60)),
                          Container(
                            width: 16,
                            height: 16,
                            child: ValueListenableBuilder(
                              valueListenable: questionTextureNotifier,
                              builder: (context, value, child) {
                                return UIUtils.getWidgetByTextureId(value as int);
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  Offstage(
                    offstage: !agreementNotifier.value,
                    child: GestureDetector(
                      onTap: () {},
                      child: Container(
                        margin: EdgeInsets.only(top: 20),
                        width: 200,
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(
                              _gestationWeek.isEmpty ? '出生孕周' : _gestationWeek,
                              style: TextStyle(
                                fontSize: 24,
                                color:
                                dateNotifier.value.isEmpty ? Colors.white54 : Colors.white,
                              ),
                            ),
                            Divider(height: 1, color: Colors.white)
                          ],
                        ),
                      ),
                    ),
                  )
                ],
              );
            },
          )
        ),
        Positioned(
            top: ScreenUtil().screenHeight / 2 + 280 / 2 + 32,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  width: 12,
                  height: 12,
                  margin: EdgeInsets.only(right: 2),
                  child: GestureDetector(
                    onTap: () {
                      agreementNotifier.value = !agreementNotifier.value;
                    },
                    child: ValueListenableBuilder(
                      valueListenable: agreementNotifier,
                      builder: (context, value, child) {
                        return UIUtils.getWidgetByTextureId(
                            value != null ? checkTextureId : uncheckTextureId);
                      },
                    ),
                  ),
                ),
                RichText(
                  text: TextSpan(
                      style: TextStyle(fontSize: 14, color: Colors.white),
                      children: [
                        TextSpan(text: '已阅读并同意 '),
                        TextSpan(
                            text: '使用条款与隐私政策',
                            style: TextStyle(
                                fontSize: 14,
                                color: Colors.white,
                                decoration: TextDecoration.underline),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                /// TODO : 跳转使用条款与隐私政策
                                /// Navigator.of(context).pushNamed('login');
                              }),
                      ]),
                )
              ],
            )),
        Positioned(
          top: ScreenUtil().screenHeight / 2 + 280 / 2 + 32 + 40,
          child: FlatButton(
            // minWidth: 200,
            // height: 54,
            fontSize: 20,
            minimumSize: Size(200, 54),
            textColor: Colors.white,
            disabledTextColor: Colors.white,
            backgroundColor: Colors.white70,
            onPressed: (!agreementNotifier.value ||
                    dateNotifier.value.isEmpty ||
                    (prematureNotifier.value && _gestationWeek.isEmpty))
                ? null
                : () {
                    String birthday =
                        DateTime.parse(dateNotifier.value).millisecondsSinceEpoch.toString();
                    ApiUtils.inst
                        .addAccountChild(
                            birthday: birthday,
                            expectedDate: birthday,
                            gestationStatus: statusChangeNotifier!._gestation.toString())
                        .then((value) {
                      if (value.isSuccess) {
                        UserDatabaseUtil.inst.database.childDao
                            .insertChild(value.data!.accountChild);
                        Navigator.of(context)
                            .popAndPushNamed(RoutePage.PAGE_REG_LOGIN);
                      }
                    });
                  },
            fontWeight: FontWeight.bold,
            child: Text('完成'),
            shape: RoundedRectangleBorder(
                side: BorderSide(color: Colors.white),
                borderRadius: BorderRadius.all(Radius.circular(27))),
          ),
        ),
      ],
    );
  }

  Future<void> loadImageWithTexture() async {
    int questionId = -1;

    try {
      questionId = await IvyBabyRecord.loadImage('initial_question_bg');
    } on PlatformException {
      print('loadImage exception!');
    }

    if (!mounted) return;

    questionTextureNotifier.value = questionId;
  }
}

class StatusChangeNotifier extends ChangeNotifier {
  int _gestation = -1;

  void update(int status) {
    _gestation = status;
    notifyListeners();
  }
}
